<template>
  <div ref="container" class="container" style="width:100%;height:100%; overflow: initial" v-loading="viewLoading">
    <!-- 尺寸缩放 -->
    <div class="size-wrapper" :style="{transform: 'scale('+zoom+')'}">
      <!-- 背景 -->
      <div class="bg" :style="{
                  backgroundImage: backgroundImage,
                  backgroundColor: pageInfo.backgroundColor,
            }">
        <!--  舞台 -->
        <div class="stage" :style="{
                  width: pageInfo.width + 'px',
                  height: pageInfo.height + 'px',
               }">
          <!-- 全局数据源加载-->
          <global-data v-for="item in globalDataSourceList"
                       :ref="'widget-'+item.uuid"
                       :key="item.uuid"
                       :val="item"
                       :pageParams="params"
                       mode_="view"
                       @dataUpdate="onGlobalDataUpdate"
          />

          <!--  组件  -->
          <template v-for="item in widgetList">
            <!--  特殊复杂组件  -->
            <component v-if="item.complex"
                       :ref="'widget-'+item.uuid"
                       :key="item.uuid"
                       :is="item.type" :val="item"
                       mode_="view"
                       disabled
                       :globalData="globalData"
                       :pageInfo="pageInfo"/>

            <!--  一般组件  -->
            <div v-else class="view-item" :key="item.uuid"
                 :style="{
              left: item.x+'px',
              top: item.y+'px',
              width: item.w+'px',
              maxHeight: item.h+'px',
              zIndex: item.z
              }">
              <component :ref="'widget-'+item.uuid" :is="item.type" :val="item" :pageParams="params" mode_="view"
                         :globalData="globalData"/>

              <!--  容器内子组件  -->
              <div class="view-item"
                   v-for="child in getChildren(item.uuid)" :key="child.uuid"
                   :style="{
                left: child.x+'px',
                top: child.y+'px',
                width: child.w+'px',
                maxHeight: child.h+'px',
                zIndex: child.z
                }"
              >
                <component :ref="'widget-'+item.uuid" :is="child.type" :val="child" :pageParams="params" mode_="view"
                           :globalData="globalData"/>
              </div>
            </div>
          </template>

        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import Vue from 'vue';
  import vpd from './mixins/vpd';
  import {getView} from '@/api/iot/view';
  import widgetInstall from './plugins/widget';
  import widgets from '../widgets';
  import dataSources from '../dataSource/index.js';
  import GlobalData from '../widgets/globalData';

  export default {
    name: 'VpdView',
    mixins: [vpd],
    components: {
      GlobalData
    },
    props: {
      id: {
        type: [Number, String]
      },
      options: {
        type: Object
      }
    },
    data() {
      return {
        params: {},

        view: {},
        viewLoading: false,
        content: {},
        zoom: 1,
        globalData: {}
      }
    },

    computed: {
      pageInfo() {
        return this.content.page || {};
      },
      // 已添加的组件
      widgetStore() {
        return this.content.widgets || [];
      },
      widgetList() {
        return this.widgetStore.filter(item => !item.parent);
      },
      globalDataSourceList() {
        return this.content.dataSources || [];
      },
      backgroundImage() {
        if (this.pageInfo.backgroundImg) {
          return 'url("' + process.env.VUE_APP_BASE_API + this.pageInfo.backgroundImg + '")';
        }
        return null;
      },
    },
    watch: {
      $route: function (route) {
        this.init();
      }
    },
    created() {
      // 注册 widgets
      Vue.use(widgetInstall, {
        widgets: widgets.all()
      });
    },
    mounted() {
      this.init();
    },
    beforeDestroy() {
      // console.log('view beforeDestroy');
    },
    methods: {
      init() {
        // console.log('view mounted');
        //可以router传参或者组件传参
        //页面id
        const id = this.$route.query.id || this.id;
        //页面需要的参数
        this.params = this.$route.query || this.options;

        // 红外传感器的code=sNum&gNum，特殊处理
        if (this.params.deviceCode && this.params.deviceCode.indexOf('&') !== -1) {
          const arr = this.params.deviceCode.split('&');
          this.params['sNum'] = arr[0];
          this.params['gNum'] = arr[1];
        }
        this.getViewInfo(id);
      },
      getViewInfo(id) {
        this.viewLoading = true;
        getView(id).then(res => {
          this.view = res.data;
          // 初始化已有数据
          if (this.view.content) {
            this.content = JSON.parse(this.view.content);
            this.doZoom();
          }
        }).finally(() => {
          this.$nextTick(() => {
            this.viewLoading = false;
          });

        })
      },
      getChildren(parentId) {
        return this.widgetStore.filter(item => item.parent === parentId);
      },
      /**
       *缩放处理，保证不出现横向滚动条
       */
      doZoom() {
        const container = this.$refs.container;
        const w = container.clientWidth;
        console.log('container.clientWidth', w, this.pageInfo.width);
        if (w < this.pageInfo.width) {
          this.zoom = w / this.pageInfo.width;
        } else {
          this.zoom = 1;
        }
      },
      /**
       * 全局数据源-数据更新时
       */
      onGlobalDataUpdate(e) {
        this.$set(this.globalData, e.key, e.value);
      }
    }
  }
</script>
<style scoped>
  .container {
    overflow: auto;
    position: relative;
  }

  .size-wrapper {
    position: absolute;
    transform-origin: left top 0;
    will-change: transform;
  }

  .bg {
    background-color: #fff;
    background-repeat: no-repeat;
    background-attachment: scroll;
    background-position: center;
    background-size: cover;
  }

  .stage {
    /*border: 1px solid #ccc;*/
    position: relative;
    overflow: hidden;
  }

  .view-item {
    position: absolute;
  }

</style>
